// 使用 node 模拟 http1 过程
const http = require("http");
const path = require("path");
const fs = require("fs");
const url = require("url");

const staticDir = path.join(__dirname, "static");
const server = http.createServer((req, res) => {
  let { pathname } = url.parse(req.url);
  if (pathname == "/favicon.ico") return;
  console.log(pathname);
  if (pathname === "/") {
    pathname = "/index.html";
    fs.createReadStream(path.join(__dirname, "index.html")).pipe(res);
  } else {
    let reqUlr = path.join(staticDir, "../", pathname);
    try {
      fs.accessSync(reqUlr);
      fs.createReadStream(reqUlr).pipe(res);
    } catch (e) {
      console.log(e, "err");
      res.statusCode = 404;
      res.end("not found");
    }
  }
});
server.listen(3001, () => {
  console.log("server listening on 3001");
});
